<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>🖼️ 图片批量插入到 Word 文档</title>
    <!-- 本地引用Tailwind CSS -->
    <script src="../../assets/js/tailwind.min.js"></script>
    <!-- docx.js（保持不变） -->
    <script src="../../assets/js/docx.min.js"></script>
</head>
<body class="bg-slate-100 text-slate-800 font-sans">

    <div class="max-w-2xl mx-auto my-8 p-6 sm:p-8 bg-white rounded-2xl shadow-lg">
    <h1 class="text-3xl font-bold text-center mb-6">🖼️ 图片批量插入到 Word 文档</h1>

    <!-- 上传区 -->
    <div id="drop-area"
            class="border-2 border-dashed border-sky-400 hover:border-sky-600 bg-sky-50 hover:bg-sky-100 transition rounded-xl p-6 text-center">
        <p class="text-slate-500 mb-4">📁 点击选择文件夹或直接把文件夹拖拽到此处</p>
        <button id="select-folder"
                class="bg-sky-500 hover:bg-sky-600 text-white font-semibold px-5 py-2 rounded-lg transition">
        选择图片文件夹
        </button>
        <input type="file" id="folder-input" webkitdirectory directory multiple class="hidden" />
        <!-- 文件列表 -->
        <div id="file-list" class="hidden mt-4 max-h-48 overflow-y-auto border rounded-md p-3 bg-white text-sm"></div>
    </div>

    <!-- 进度条 -->
    <div id="progress-container" class="hidden mt-6">
        <div class="w-full bg-slate-200 rounded-full h-6 overflow-hidden">
        <div id="progress-bar" class="bg-green-500 h-6 rounded-full transition-all duration-300 w-0"></div>
        </div>
        <p id="progress-text" class="text-center text-sm mt-1 text-slate-600">准备中…</p>
    </div>

    <!-- 信息提示 -->
    <div id="info-box" class="hidden mt-6 p-4 border-l-4 border-sky-500 bg-sky-50 text-sky-700 rounded-r-md"></div>

    <!-- 生成按钮 -->
    <button id="generate-btn" disabled
            class="mt-6 w-full sm:w-auto mx-auto block bg-green-500 hover:bg-green-600 disabled:bg-slate-300 text-white font-semibold px-8 py-2 rounded-lg transition">
        🚀 生成 Word 文档
    </button>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function() {
            const selectFolderBtn = document.getElementById('select-folder');
            const folderInput = document.getElementById('folder-input');
            const generateBtn = document.getElementById('generate-btn');
            const dropArea = document.getElementById('drop-area');
            const progressContainer = document.getElementById('progress-container');
            const progressBar = document.getElementById('progress-bar');
            const progressText = document.getElementById('progress-text');
            const infoBox = document.getElementById('info-box');
            const fileList = document.getElementById('file-list');
            
            let selectedFiles = [];
            
            selectFolderBtn.addEventListener('click', () => {
                folderInput.value = '';
                folderInput.click();
            });
            
            folderInput.addEventListener('change', async (event) => {
                const files = Array.from(event.target.files);
                await processFiles(files);
            });
            
            dropArea.addEventListener('dragover', (e) => {
                e.preventDefault();
                dropArea.classList.add('drag-over');
            });
            
            dropArea.addEventListener('dragleave', () => {
                dropArea.classList.remove('drag-over');
            });
            
            dropArea.addEventListener('drop', async (e) => {
                e.preventDefault();
                dropArea.classList.remove('drag-over');
                
                if (e.dataTransfer.items) {
                    const entries = [];
                    for (let i = 0; i < e.dataTransfer.items.length; i++) {
                        const entry = e.dataTransfer.items[i].webkitGetAsEntry();
                        if (entry) entries.push(entry);
                    }
                    const files = await getFilesFromEntries(entries);
                    await processFiles(files);
                }
            });
            
            generateBtn.addEventListener('click', generateWordDocument);
            
            async function getFilesFromEntries(entries) {
                const files = [];
                
                for (const entry of entries) {
                    if (entry.isFile) {
                        const file = await new Promise(resolve => entry.file(resolve));
                        files.push(file);
                    } else if (entry.isDirectory) {
                        const dirReader = entry.createReader();
                        const entries = await new Promise(resolve => {
                            dirReader.readEntries(resolve);
                        });
                        const subFiles = await getFilesFromEntries(entries);
                        files.push(...subFiles);
                    }
                }
                
                return files;
            }
            
            async function processFiles(files) {
                selectedFiles = files.filter(file => 
                    ['image/png', 'image/jpeg', 'image/gif', 'image/bmp'].includes(file.type)
                );
                
                if (selectedFiles.length === 0) {
                    showInfo('未找到图片文件，请选择包含图片的文件夹', 'error');
                    generateBtn.disabled = true;
                    fileList.style.display = 'none';
                    return;
                }
                
                fileList.innerHTML = '';
                selectedFiles.forEach(file => {
                    const fileItem = document.createElement('div');
                    fileItem.className = 'file-item';
                    
                    const fileName = document.createElement('span');
                    fileName.className = 'file-name';
                    fileName.textContent = file.name;
                    
                    const fileSize = document.createElement('span');
                    fileSize.className = 'file-size';
                    fileSize.textContent = formatFileSize(file.size);
                    
                    fileItem.appendChild(fileName);
                    fileItem.appendChild(fileSize);
                    fileList.appendChild(fileItem);
                });
                
                fileList.style.display = 'block';
                showInfo(`已选择 ${selectedFiles.length} 张图片`, 'success');
                generateBtn.disabled = false;
            }
            
            function formatFileSize(bytes) {
                if (bytes === 0) return '0 Bytes';
                const k = 1024;
                const sizes = ['Bytes', 'KB', 'MB', 'GB'];
                const i = Math.floor(Math.log(bytes) / Math.log(k));
                return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
            }
            
            async function generateWordDocument() {
                if (selectedFiles.length === 0) {
                    showInfo('请先选择包含图片的文件夹', 'error');
                    return;
                }
                
                progressContainer.style.display = 'block';
                progressBar.style.width = '0%';
                progressText.textContent = '准备中...';
                generateBtn.disabled = true;
                
                try {
                    // 创建新文档
                    const doc = new docx.Document({
                        creator: "图片转Word工具",
                        description: "由图片生成的Word文档",
                        title: "图片文档",
                        styles: {
                            paragraphStyles: [
                                {
                                    id: "Normal",
                                    name: "Normal",
                                    run: {
                                        size: 24,
                                    },
                                    paragraph: {
                                        spacing: {
                                            line: 276,
                                        },
                                    },
                                },
                            ],
                        },
                        numbering: {
                            config: []
                        },
                        sections: []
                    });
                    
                    // 设置图片固定高度为16cm（1cm = 567 dxa）
                    const fixedHeight = 16 * 56.7; // 16cm转换为dxa单位
                    
                    // 处理每张图片
                    for (let i = 0; i < selectedFiles.length; i++) {
                        const file = selectedFiles[i];
                        
                        // 更新进度
                        const progress = Math.floor((i / selectedFiles.length) * 100);
                        progressBar.style.width = `${progress}%`;
                        progressText.textContent = `正在处理图片 ${i + 1}/${selectedFiles.length} (${file.name})`;
                        
                        try {
                            // 读取图片数据并获取原始尺寸
                            const arrayBuffer = await file.arrayBuffer();
                            const img = await loadImage(file);
                            
                            // 计算保持纵横比的宽度
                            const aspectRatio = img.width / img.height;
                            const calculatedWidth = fixedHeight * aspectRatio;
                            
                            // 创建图片段落 - 锁定纵横比
                            const imageRun = new docx.ImageRun({
                                data: arrayBuffer,
                                transformation: {
                                    width: calculatedWidth,
                                    height: fixedHeight,
                                    flip: null, // 禁止翻转
                                }
                            });
                            
                            // 创建段落
                            const paragraph = new docx.Paragraph({
                                children: [imageRun],
                                spacing: {
                                    after: 400,
                                }
                            });
                            
                            // 添加section到文档
                            doc.addSection({
                                properties: {
                                    page: {
                                        size: {
                                            width: 11906, // A4宽度(21cm)
                                            height: 16838, // A4高度(29.7cm)
                                            orientation: docx.PageOrientation.PORTRAIT
                                        },
                                        margins: {
                                            top: 1440,
                                            bottom: 1440,
                                            left: 1440,
                                            right: 1440,
                                        }
                                    }
                                },
                                children: [
                                    paragraph,
                                    // 如果不是最后一张图片，添加分页符
                                    ...(i < selectedFiles.length - 1 ? [new docx.Paragraph({
                                        children: [new docx.PageBreak()]
                                    })] : [])
                                ]
                            });
                        } catch (imgError) {
                            console.error(`处理图片 ${file.name} 时出错:`, imgError);
                            showInfo(`跳过图片 ${file.name}: 格式可能不受支持`, 'error');
                            continue;
                        }
                    }
                    
                    // 生成Word文档
                    progressText.textContent = '正在生成Word文档...';
                    const blob = await docx.Packer.toBlob(doc);
                    
                    // 下载文件
                    const url = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = '图片文档.docx';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    URL.revokeObjectURL(url);
                    
                    // 完成
                    progressBar.style.width = '100%';
                    progressText.textContent = `已完成！共生成 ${selectedFiles.length} 页文档`;
                    showInfo('Word文档生成成功！', 'success');
                    
                } catch (error) {
                    console.error('生成Word文档时出错:', error);
                    progressText.textContent = '生成失败';
                    showInfo('生成Word文档时出错: ' + error.message, 'error');
                } finally {
                    generateBtn.disabled = false;
                }
            }
            
            // 辅助函数：加载图片并获取原始尺寸
            function loadImage(file) {
                return new Promise((resolve, reject) => {
                    const img = new Image();
                    const url = URL.createObjectURL(file);
                    img.onload = () => {
                        URL.revokeObjectURL(url);
                        resolve(img);
                    };
                    img.onerror = () => {
                        URL.revokeObjectURL(url);
                        reject(new Error('图片加载失败'));
                    };
                    img.src = url;
                });
            }
            
            function showInfo(message, type) {
                infoBox.textContent = message;
                infoBox.style.display = 'block';
                infoBox.style.borderLeftColor = type === 'error' ? '#e74c3c' : '#2ecc71';
                infoBox.style.backgroundColor = type === 'error' ? '#fde8e8' : '#e8f8f0';
            }
        });
    </script>
</body>
</html>